package com.hc.serviceImpl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;

import com.hc.bean.UrlBean;
import com.hc.comm.CommData;
import com.hc.dao.RunSqlDao;
import com.hc.daoImpl.RunSqlDaoImpl;
import com.hc.service.UserUrlService;

public class UserUrlServiceImpl implements UserUrlService {

	@Override
	public boolean addUrl(HttpServletRequest req, HttpServletResponse resp) {
//		int testTimes = Integer.valueOf(req.getParameter("testTimes"));
		String testUrl = req.getParameter("testUrl").trim();

		RunSqlDao dao = new RunSqlDaoImpl();
		
		dao.runSqlUpdate("insert into userUrlList (testTimes, testUrl) VALUES (" + CommData.webTestNumber + ", '" + testUrl + "')");
		updateCache();
		return true;
	}

	@Override
	public boolean updateUrl(HttpServletRequest req, HttpServletResponse resp) {
//		int testTimes = Integer.valueOf(req.getParameter("testTimes"));
		String testUrl = req.getParameter("testUrl").trim();
		int id = Integer.valueOf(req.getParameter("id"));
		RunSqlDao dao = new RunSqlDaoImpl();
		dao.runSqlUpdate("update userUrlList set testTimes = " +CommData.webTestNumber
				+ ", testUrl = '" + testUrl + "' where id = " + id);
		updateCache();
		return true;
	}
	
	@Override
	public boolean delUrl(HttpServletRequest req, HttpServletResponse resp) {
		int id = Integer.valueOf(req.getParameter("id"));
		RunSqlDao dao = new RunSqlDaoImpl();
		dao.runSqlUpdate("delete from userUrlList where id = " + id);
		updateCache();
		return true;
	}
	
	private void updateCache(){
		CommData.urls.clear();
		RunSqlDao dao = new RunSqlDaoImpl();
		List list = dao.runSqlQuery("select id, testTimes, testUrl from userUrlList");
		for(Object obj : list){
			Map map = (Map) obj;
			UrlBean bean = new UrlBean();
			bean.setId(Integer.valueOf(map.get("id").toString()));
			bean.setTestTimes(Integer.valueOf(map.get("testTimes").toString()));
			bean.setTestUrl(map.get("testUrl").toString().trim());
			CommData.urls.put(bean.getId(), bean);
		}
	}
	
	@Override
	public JSONArray getUrls() {
		List<UrlBean> list = new ArrayList<UrlBean>();
		for(UrlBean bean : CommData.urls.values()){
			list.add(bean);
		}
		return JSONArray.fromObject(list);
	}
}
